package com.zxjbyte.yiyi.framework.common.core.okhttp.callback;

import com.zxjbyte.yiyi.framework.common.core.okhttp.IResponseProcessor;
import com.zxjbyte.yiyi.framework.common.function.TriConsumer;
import org.springframework.lang.Nullable;

import java.util.function.Consumer;

/**
 * 默认的进度回调处理类
 *
 * @Author zhangxingjia
 * @Date 2024/4/28 15:20
 * @Version: 1.0
 */
public class DefaultProgressCallbackHandler extends AbstractAsyncCallback {

    private Consumer<IResponseProcessor> successConsumer;
    private Consumer<FailureContext> failureConsumer;
    private final ProgressHandler progressHandler;


    public DefaultProgressCallbackHandler(ProgressTypeEnum progressType, TriConsumer<Long, Long, Boolean> progressConsumer){
        this.failureConsumer = DEFAULT_FAIL_CONSUMER;
        this.successConsumer = DEFAULT_SUCCESS_CONSUMER;
        this.progressHandler = new ProgressHandler(progressType, progressConsumer);
    }

    public DefaultProgressCallbackHandler onFailure(Consumer<FailureContext> failureConsumer){
        this.failureConsumer = failureConsumer;
        return this;
    }

    public DefaultProgressCallbackHandler onSuccess(Consumer<IResponseProcessor> successConsumer) {
        this.successConsumer = successConsumer;
        return this;
    }


    @Override
    protected final void asFailure(@Nullable FailureContext context) {
        failureConsumer.accept(context);
    }

    @Override
    protected final void asSuccess(@Nullable IResponseProcessor processor) {
        successConsumer.accept(processor);
    }

    @Override
    public IProgressCallback getProgressCallback() {
        return this.progressHandler;
    }

    private static class ProgressHandler implements IProgressCallback {
        private TriConsumer<Long, Long, Boolean> uploadProgressConsumer;
        private TriConsumer<Long, Long, Boolean> downloadProgressConsumer;

        private ProgressHandler(ProgressTypeEnum progressType, TriConsumer<Long, Long, Boolean> progressConsumer) {
            if (progressType.equals(ProgressTypeEnum.UPLOAD)) {
                this.uploadProgressConsumer = progressConsumer;
            } else {
                this.downloadProgressConsumer = progressConsumer;
            }
        }

        @Override
        public void onUploadProgress(long bytesWritten, long contentLength, boolean done) {
            if (this.uploadProgressConsumer != null) {
                this.uploadProgressConsumer.accept(bytesWritten, contentLength, done);
            }
        }

        @Override
        public void onDownloadProgress(long bytesRead, long contentLength, boolean done) {
            if (this.downloadProgressConsumer != null) {
                this.downloadProgressConsumer.accept(bytesRead, contentLength, done);
            }
        }
    }

}
